package com.inews.base.exception;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.inews.base.mapper.JsonMapper;
import com.inews.base.utils.ExtDataUtil;
import com.inews.base.utils.Servlets;
import com.inews.base.vo.ExtData;

// TODO: Auto-generated Javadoc
/**
 * 统一异常处理.
 */
@Component
public class ExceptionHandler implements HandlerExceptionResolver {
	
	private static Logger logger = Logger.getLogger(ExceptionHandler.class);

	@Override
	public ModelAndView resolveException(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex) {
		ExtData<String> extData;
		if (ex instanceof BusinessException) {
			logger.error("业务异常:" + ex.getMessage());
			ex.printStackTrace();
			extData = ExtDataUtil.genWithErrors(ex.getMessage());
		} else {
			logger.error("系统异常:" + ex.getMessage());
			ex.printStackTrace();
			extData = ExtDataUtil.genWithErrors("服务器忙，请稍后再试...");
		}
		request.setAttribute("errorMsg", JsonMapper.nonEmptyMapper().toJson(extData));
		if (Servlets.isAjax(request)) {
			return new ModelAndView("errorMsg");
		}else{
			return new ModelAndView("500");
		}

	}

}
